import { defineStore } from "pinia";
import requests from "../utils/requests";

const useHistoryStore=defineStore('history',{
	state:()=>({
		historyList:[],
		show:0,
		page:1,
		finish:false,
		date:null,
	}),
	actions:{
		async searchHistory(){
			const params={
				username:uni.getStorageSync('username'),
				page:this.page
			}
			const res=await requests({
				url:'/base/locationHistory/',
				method:'get',
				data:params
			})
			if(res.code===200){
				if(res.data.length===0){
					this.show=1
				}else{
					for (let item in res.data){
						this.historyList.push(res.data[item])
					}
					this.show=2
				}
			}else if(res.detail==='无效页面。'){
				this.finish=true
			}else{
				uni.$u.toast(`查询失败，${res.error}`)
			}
		},
		async dateSearchHistory(){
			const params={
				username:uni.getStorageSync('username'),
				page:this.page
			}
			const date = new Date(this.date);
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			const formattedDate = `${year}-${month}-${day}`;
			params.submit_time=formattedDate
			const res=await requests({
				url:'/base/locationHistory/',
				method:'get',
				data:params
			})
			if(res.code===200){
				if(res.data.length===0){
					this.show=1
				}else{
					for (let item in res.data){
						this.historyList.push(res.data[item])
					}
					this.show=2
				}
			}else if(res.detail==='无效页面。'){
				this.finish=true
			}else{
				uni.$u.toast(`查询失败，${res.error}`)
			}
		},
		async firstDate(){
			this.page=1
			const params={
				username:uni.getStorageSync('username'),
				page:this.page
			}
			const date = new Date(this.date);
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			const formattedDate = `${year}-${month}-${day}`;
			params.submit_time=formattedDate
			const res=await requests({
				url:'/base/locationHistory/',
				method:'get',
				data:params
			})
			if(res.code===200){
				if(res.data.length===0){
					this.show=1
				}else{
					this.historyList=res.data
					this.show=2
				}
			}else if(res.detail==='无效页面。'){
				this.finish=true
			}else{
				uni.$u.toast(`查询失败，${res.error}`)
			}
			this.date=null
		},
		async loadHistory(){
			if(this.finish===false){
				this.page+=1
				await this.searchHistory()
			}else{
				uni.$u.toast('暂无更多历史记录')
			}
		}
	}
})
export default useHistoryStore;